import moment from 'moment'
import { nextTick, reactive, watch, ref, computed } from 'vue'
export default class PageProgress {
  constructor(options = {}) {
    this.now = 0
    this.total = options.total
    this.records = reactive([])
    this.percent = ref(0)
    watch(this.records, () => {
      //这里保留了一开始的this
      //因为这边赋值的this是一开始的，所以两个不同的对象不搭嘎，所以菜无法渲染
      this.computedNow()
    })
  }
  add(data) {
    this.records.push(new PageProgressRecord(data))
  }
  del(record) {
    let index = this.records.indexOf(record)
    if (index > -1) {
      this.records.splice(index, 1)
    }
  }
  computedNow() {
    this.now = this.records.reduce((memo, res) => memo + res.progress, 0)
    this.percent.value = Math.floor(this.total == 0 ? 0 : (this.now / this.total) * 100)
    console.log(`computedNow`)
  }
  toJSON() {
    console.log(this.percent)
    return {
      now: this.now.value,
      records: this.records.map((res) => res.toJSON())
    }
  }
  fromJSON(json) {
    this.now = json.now
    this.records.length = 0
    json.records.forEach((res) => {
      this.records.push(new PageProgressRecord().fromJSON(res))
    })
    return this
  }
}

class PageProgressRecord {
  constructor(options = {}) {
    this.time = options.time
    this.note = options.note
    this.progress = options.progress
  }
  toJSON() {
    return {
      time: this.time,
      note: this.note,
      progress: this.progress
    }
  }
  fromJSON(json) {
    this.name = json.name
    this.note = json.note
    this.progress = json.progress
    this.time = json.time
    return this
  }
  formatTime() {
    if (this.time) {
      return moment(this.time).format('YYYY-MM-DD')
    } else {
      return moment().format('YYYY-MM-DD')
    }
  }
  edit(form) {
    this.time = form.time
    this.note = form.note
    this.progress = form.progress
  }
}
